﻿using UnityEditor;
using UnityEngine;

namespace EditorFramework
{
    public static class DragAndDropTool
    {
        public class DragInfo
        {
            public bool EnterArea;
            public bool Dragging;
            public bool Complete;

            public Object[] ObjectReferences => DragAndDrop.objectReferences;
            public string[] Paths => DragAndDrop.paths;
            public DragAndDropVisualMode VisualMode => DragAndDrop.visualMode;
            public int ActiveControlID => DragAndDrop.activeControlID;
        }

        private static DragInfo mDragInfo = new DragInfo();
        private static bool mEnterArea;
        private static bool mDragging;
        private static bool mComplete;

        public static DragInfo Drag(Event current, Rect rect, DragAndDropVisualMode mode = DragAndDropVisualMode.Generic)
        {
            var e = Event.current;
            mEnterArea = rect.Contains(e.mousePosition);
            if (e.type == EventType.DragUpdated) // 拖曳更新
            {
                mDragging = true;
                mComplete = false;
                if (rect.Contains(e.mousePosition))
                {
                    DragAndDrop.visualMode = DragAndDropVisualMode.Generic; // 改变鼠标样式
                    e.Use(); // 不再监听事件
                }
            }
            else if (e.type == EventType.DragPerform) // 拖拽生效
            {
                mDragging = false;
                mComplete = true;
                DragAndDrop.AcceptDrag(); // 允许目标窗口接收拖拽的资源
                e.Use();
            }
            else if (e.type == EventType.DragExited) // 拖拽到区域外
            {
                mDragging = false;
                mComplete = true;
            }
            else
            {
                mDragging = false;
                mComplete = false;
            }

            mComplete = mComplete && e.type == EventType.Used;
            mDragInfo.EnterArea = mEnterArea;
            mDragInfo.Dragging = mDragging;
            mDragInfo.Complete = mComplete;

            return mDragInfo;
        }
    }
}